﻿using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

/// <summary>
/// 逻辑处理类
/// </summary>
public class BattleLogic
{
    /// <summary>
    /// 当前分数
    /// </summary>
    private int current_score;

    /// <summary>
    /// 历史最高分
    /// </summary>
    private int history_highest_score;

    /// <summary>
    /// 是否暂停
    /// </summary>
    private bool isPause;

    /// <summary>
    /// 是否已经输了
    /// </summary>
    private bool isLose;

    /// <summary>
    /// 当前血量他
    /// </summary>
    private int current_blood;

    /// <summary>
    /// 当前难度
    /// </summary>
    private int current_diffculty = 0;

    /// <summary>
    /// 单例类
    /// </summary>
    private static BattleLogic _battleLogic;

    /// <summary>
    /// 玩家手中的牌
    /// </summary>
    private static List<string> playerCardPool;

    /// <summary>
    /// 当前选择的角色名字
    /// </summary>
    private string cur_select_role_name = "f_10";

    /// <summary>
    /// 选择角色名字
    /// </summary>
    /// <param name="name"></param>
    public void SetCurentRoleName(string name)
    {
        cur_select_role_name = name;
    }
    
    /// <summary>
    /// 当前选择的角色名字
    /// </summary>
    /// <returns></returns>
    public string GetCurrentRoleName()
    {
        return cur_select_role_name;
    }


    /// <summary>
    /// getInstance
    /// </summary>
    /// <returns></returns>
    public static BattleLogic getInstance()
    {
        if (_battleLogic == null)
        {
            _battleLogic = new BattleLogic();
        }

        return _battleLogic;
    }

    /// <summary>
    /// 设置当前血量
    /// </summary>
    public void SetCurrentBlood(int current_blood)
    {
        this.current_blood = current_blood;
    }

    /// <summary>
    /// 获取当前血量
    /// </summary>
    /// <returns></returns>
    public int GetCurrentBlood()
    {
        return current_blood;
    }

    /// <summary>
    /// 初始化数据
    /// </summary>
    public void InitData()
    {
        current_blood = GameConfig.BLOOD_START;
        current_score = GameConfig.SCORE_START;
        history_highest_score = PlayerPrefs.GetInt(GameConfig.modeKey[current_diffculty]);
        isPause = false;
        isLose = false;
        playerCardPool = new List<string>();
    }

    /// <summary>
    /// 设置当前难度
    /// </summary>
    public void setDiffculty(int diffculty)
    {
        if (diffculty >= 0 && diffculty <= 2)
        {
            current_diffculty = diffculty;
        }
        else
        {
            Debug.LogError("难度设置不合法" + diffculty);
        }
    }

    /// <summary>
    /// 获取当前难度
    /// </summary>
    public int getDiffculty()
    {
        return current_diffculty;
    }


    /// <summary>
    /// AddPlayerCardPool 
    /// </summary>
    /// <param name="card"></param>
    public void AddPlayerCardPool(string cardSpriteName)
    {
        playerCardPool.Add(cardSpriteName);
    }

    /// <summary>
    /// RemovePlayerCardPool
    /// </summary>
    /// <param name="cardSpriteName"></param>
    public void RemoveCardFromPlayerCardPool(string cardSpriteName)
    {
        if (playerCardPool.Contains(cardSpriteName))
        {
            playerCardPool.Remove(cardSpriteName);
        }
    }

    /// <summary>
    /// GetCardNumInPlayer(获取当前手牌的数量)
    /// </summary>
    public int GetCardNumInPlayer()
    {
        return playerCardPool.Count;
    }

    /// <summary>
    /// 随机一个可以删除的(移除道具)
    /// </summary>
    /// <returns></returns>
    public string RandomRemoveCardInPool()
    {
        int random_index = Random.Range(0, playerCardPool.Count);
        string element = playerCardPool[random_index];
        return element;
    }

    /// <summary>
    /// 是否已经输了
    /// </summary>
    /// <returns></returns>
    public bool GetIsLose()
    {
        return isLose;
    }

    /// <summary>
    /// 是否已经暂停
    /// </summary>
    /// <returns></returns>
    public bool GetIsPause()
    {
        return isPause;
    }

    /// <summary>
    /// 设置暂停
    /// </summary>
    public void SetIsPause(bool isPause)
    {
        this.isPause = isPause;
    }
    /// <summary>
    /// 设置当前分数
    /// </summary>
    public void SetCurrentScore(int currentScore)
    {
        current_score = currentScore;
        // Debug.Log("currentScore-------------------------"+currentScore);
        // Debug.Log("history_highest_score-------------------------"+history_highest_score);
        //当前分数高于历史分数更新历史分数
        if (currentScore > history_highest_score)
        {
            history_highest_score = currentScore;
            string currentKey = GameConfig.modeKey[current_diffculty];
            PlayerPrefs.SetInt(currentKey, history_highest_score);
        }
    }

    /// <summary>
    /// 获取当前分数
    /// </summary>
    /// <returns></returns>
    public int GetCurrentScore()
    {
        return current_score;
    }

    /// <summary>
    /// 获取本地缓存数据
    /// </summary>
    /// <returns></returns>
    public PlayerPrefsData GetLocalPlayerData()
    {
        int highestScore = PlayerPrefs.GetInt(GameConfig.modeKey[current_diffculty]);
        PlayerPrefsData playerData = new PlayerPrefsData();
        playerData.setHighestScore(highestScore);
        return playerData;
    }

    /// <summary>
    /// 随机障碍物
    /// </summary>
    public ObstacleDataModel GetRandomObstacle()
    {
        int random_Obstacle_kind = Random.Range(GameConfig.OBSTACLE_INTERVAL_MIN, GameConfig.OBSTACLE_INTERVAL_MAX + 1);
        ObstacleDataModel _obstacleDataModel = new ObstacleDataModel();

        // 随机摸牌
        if (random_Obstacle_kind >= GameConfig.OBSTACLE_INTERVAL_MIN &&
            random_Obstacle_kind <= GameConfig.MOPAI_RANDOM_MAX)
        {
            ///随机摸牌
            _obstacleDataModel.setCardSpriteName("tb_mopai");
            _obstacleDataModel.SetKind(1);
            return _obstacleDataModel;
        }

        if (random_Obstacle_kind > GameConfig.MOPAI_RANDOM_MAX && random_Obstacle_kind <= GameConfig.QIPAI_RANDOM_MAX)
        {
            ///随机丢手牌
            _obstacleDataModel.setCardSpriteName("tb_qipai");
            _obstacleDataModel.SetKind(2);
            return _obstacleDataModel;
        }

        if (random_Obstacle_kind > GameConfig.QIPAI_RANDOM_MAX && random_Obstacle_kind <= GameConfig.ZHADAN_RANDOM_MAX)
        {
            ///炸弹
            _obstacleDataModel.setCardSpriteName("tb_zhadan");
            _obstacleDataModel.SetKind(3);
            return _obstacleDataModel;
        }

        if (random_Obstacle_kind > GameConfig.ZHADAN_RANDOM_MAX &&
            random_Obstacle_kind <= GameConfig.OBSTACLE_INTERVAL_MAX)
        {
            _obstacleDataModel = BattleCardPoolLogic.getInstance().randomGetCardInPool();
            return _obstacleDataModel;
        }

        Debug.LogError("随机出现意外状况" + random_Obstacle_kind);
        return _obstacleDataModel;
    }

    /// <summary>
    /// 检测玩家卡牌是否有顺子，有顺子就移除(大于等3张)
    /// </summary>
    public List<string> CheckPlayerCardPool()
    {
        List<string> needToDeleteList = new List<string>();
        if (playerCardPool.Count < 3)
        {
            return needToDeleteList;
        }

        ///字典
        List<int> array = new List<int>();
        Dictionary<int, ObstacleDataModel> dic = new Dictionary<int, ObstacleDataModel>();
        for (int index = 0; index < playerCardPool.Count; index++)
        {
            ObstacleDataModel ob = new ObstacleDataModel();
            ob.SetKind(4);
            ob.setCardSpriteName(playerCardPool[index]);
            int cardNum = BattleCardPoolLogic.getInstance().spriteNameToCardNum(playerCardPool[index]);
            ob.SetCardNum(cardNum);
            dic.Add(cardNum, ob);
            if (!array.Contains(ob.GetLogicValue()))
            {
                array.Add(ob.GetLogicValue());
            }
        }

        List<int> arrayShunZi = GetShunZI(array);
        string showText = "需要移除的牌为";
        for (int index = 0; index < arrayShunZi.Count; index++)
        {
            string spriteName = GetFromPlayerCardPool(arrayShunZi[index], dic);
            playerCardPool.Remove(spriteName);
            needToDeleteList.Add(spriteName);
            showText = showText + "[" + spriteName + "]";
        }

        if (needToDeleteList.Count > 0)
        {
            Debug.Log(showText);
        }

        return needToDeleteList;
    }

    /// <summary>
    /// 从玩家卡组中移除顺子牌
    /// </summary>
    /// <param name="spriteName"></param>
    /// <returns></returns>
    private string GetFromPlayerCardPool(int logicValue, Dictionary<int, ObstacleDataModel> dic)
    {
        if (dic.Count <= 0)
            return null;

        foreach (ObstacleDataModel ob in dic.Values)
        {
            if (ob.GetLogicValue() == logicValue)
            {
                return ob.GetCardSpriteName();
            }
        }

        return null;
    }


    /// <summary>
    /// arrry从小到大排序 并且是唯一元素
    /// </summary>
    /// <param name="array"></param>
    /// <returns></returns>
    public List<int> GetShunZI(List<int> array)
    {
        List<int> getValueList = new List<int>();
        //从小到大排序
        array.Sort();
        int target = 0;
        while (target < array.Count)
        {
            getValueList.Add(array[target]);
            if (target + 1 < array.Count && array[target] + 1 == array[target + 1]
                                         && array[target] != 13 && array[target + 1] != 13)
            {
            }
            else
            {
                if (getValueList.Count < 3)
                {
                    getValueList.Clear();
                }
                else
                {
                    break;
                }
            }

            target++;
        }

        // for (int index = 0; index < getValueList.Count; index++)
        // {
        //     Debug.LogError(getValueList[index]+",");
        // }

        return getValueList;
    }
}